package charpter11.lynx;

import holding.InterfaceVsIterator;

import java.util.Collection;
import java.util.Iterator;

import typeinfo.pets.Pet;
import typeinfo.pets.Pets;

public class Thirty implements Collection<Pet> {

	private Pet[] pets = Pets.createArray(8);
	private int index = 0;
	
	@Override
	public boolean add(Pet e) {
		if (index < 8){
			pets[index] = e;
			return true;
		}
		return false;
	}

	@Override
	public boolean addAll(Collection<? extends Pet> c) {
		if (c.size() < 8 - index){
			for (Pet pet : c) {
				pets[index++] = pet;
			}
			return true;
		}
		return false;
	}

	@Override
	public void clear() {
		index = 0;
	}

	@Override
	public boolean contains(Object o) {
		for (Pet pet : pets) {
			if (pet.equals(o)){
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		for (Object object : c) {
			for (Pet pet : pets) {
				if (!object.equals(pet)){
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public boolean isEmpty() {
		return index == 0;
	}

	@Override
	public Iterator<Pet> iterator() {
		return new Iterator<Pet>() {
			private int next = 0;
			
			@Override
			public boolean hasNext() {
				return next < index;
			}

			@Override
			public Pet next() {
				return pets[next++];
			}

			@Override
			public void remove() {
				for(int i = next; i < index - 1; i ++){
					pets[i] = pets[i + 1];
				}
				pets[index - 1] = null;
				index = index -1;
			}
		};
	}

	@Override
	public boolean remove(Object o) {
		for (int i =0; i < index; i++){
			if (pets[i].equals(o)){
				for(int j = i; j < index - 1; j ++){
					pets[j] = pets[j + 1];
				}
				pets[index - 1] = null;
				index -= 1;
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		boolean ret = true;
		for (Object object : c) {
			if (!remove(object)){
				ret = false;
			}
		}
		return ret;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Object[] toArray() {
		return pets;
	}

	@Override
	public <T> T[] toArray(T[] a) {
		throw new UnsupportedOperationException();
	}

	public static void main(String[] args) {
	    Thirty c = new Thirty();
	    InterfaceVsIterator.display(c);
	    InterfaceVsIterator.display(c.iterator());
	  }
}
